package com.ityj.yygh.order.controller.api;

import com.ityj.yygh.enums.PaymentTypeEnum;
import com.ityj.yygh.order.service.PaymentInfoService;
import com.ityj.yygh.order.service.WeiXinService;
import com.ityj.yygh.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Api(value = "微信支付接口")
@RestController
@RequestMapping("/api/order/weixin")
@Slf4j
public class WxPayApiController {

    @Autowired
    private WeiXinService weiXinService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    // 生成微信支付二维码数据
    @GetMapping("createNative/{orderId}")
    public Result<Map<String, Object>> createNative(@PathVariable Long orderId) {
        Map<String, Object> result = weiXinService.createNative(orderId);
        return Result.ok(result);
    }

    @ApiOperation(value = "查询支付状态")
    @GetMapping("/queryPayStatus/{orderId}")
    public Result queryPayStatus(@PathVariable Long orderId) {
        // 调用微信支付状态查询接口
        Map<String, String> resultMap = weiXinService.queryPayStatus(orderId);

        if(resultMap == null) {
            log.error("支付出错");
            return Result.fail().message("支付异常");
        }
        if ("SUCCESS".equals(resultMap.get("trade_state"))) {
            // 更新订单状态，处理支付结果
            paymentInfoService.paySuccess(PaymentTypeEnum.WEIXIN.getStatus(), resultMap);
            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
    }


}
